<?php
namespace app\hotback\controller;
use think\Db;
use app\service\CouponService;
use think\Request;

class Coupon extends Base
{
	public function _initialize()
	{
		// 调用父类前置方法
		parent::_initialize();

		// 登录校验
		$this->IsLogin();
	}

	/**
	 * 优惠券列表
	 */
	public function index()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		if(request()->isPost())
		{
			$params = input();
			if(!empty($params['page']) && !empty($params['limit']))
			{
				$map = [
					'is_delete_time' => 0
				];
				if(!empty($params['name']))
				{
					$map['name'] = ['like','%'.$params['name'].'%'];
				}
				$count = Db::name('coupon')->where($map)->count();
				$list_data = Db::name('coupon')->where($map)->order('id desc')->limit(($params['page']-1)*$params['limit'],$params['limit'])->select();
				if(!empty($list_data))
				{
					//遍历处理
					foreach($list_data as $key => $value)
					{
						//编辑url
						$list_data[$key]['save_url'] = url('Coupon/saveinfo', ['id' => $value['id']]);
					}
					$result['code'] = 0;
	        		$result['msg'] = "请求成功";
	        		$result['data'] = $list_data;
	        		$result['count'] = $count;
				}else
				{
					$result['code'] = -1;
	        		$result['msg'] = "暂无数据";
				}
			}
			echo json_encode($result);
		}else
		{
			return $this->fetch();
		}
	}

	/**
	 * 优惠券添加/修改 页面
	 */
	public function saveinfo()
	{
		// 参数
		$params = input();
		$info = [];
		if(!empty($params['id']))
		{
			//查询
			$info = Db::name('coupon')->where(['id' => $params['id']])->find();
			if(!empty($info))
			{
				$info['fixed_time_start_time'] = !empty($info['fixed_time_start']) ? date('Y-m-d H:i:s', $info['fixed_time_start']) : '';
				$info['fixed_time_end_time'] = !empty($info['fixed_time_end']) ? date('Y-m-d H:i:s', $info['fixed_time_end']) : '';
			}
		}
		$this->assign('info',$info);

        $send = [];
        if (!empty($info['send_proxy'])){
            $send = json_decode($info['send_proxy']);
        }
        $this->assign('send',$send);
        $proxy_list = Db::name('proxy')->where('is_delete_time',0)->field('proxy_id,company_name')->select();
        $this->assign('proxy',$proxy_list);
		//优惠券类型
		$coupon_type_array = CouponService::$coupon_type_array;
		$this->assign('coupon_type_array', $coupon_type_array);
		//优惠券发放场景
		$send_scene_array = CouponService::$send_scene_array;
		$this->assign('send_scene_array', $send_scene_array);
//        dump($info);die;

		return $this->fetch();
	}

	/**
	 * 优惠券添加/修改
	 */
	public function save()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		if(request()->isPost())
		{
			$params = input();
			$validate = $this->validate(
				$params,
				[
					'name' => 'require|unique:coupon,is_delete_time=0&name='.$params['name'],
					'coupon_type' => 'require',
					'discount_price' => ['require', 'regex' => '^([0-9]{1}\d{0,6})(\.\d{1,2})?$', 'egt' => 0.01],
					'expire_type' => 'require',
					'expire_hour' => 'requireIf:expire_type,0|integer|gt:0',
					'fixed_time_start' => 'requireIf:expire_type,1',
					'fixed_time_end' => 'requireIf:expire_type,1',
					'where_order_price' => ['require', 'regex' => '^([0-9]{1}\d{0,6})(\.\d{1,2})?$', 'gt' => 'discount_price'],
					'limit_send_count' => 'integer|egt:0',
					'send_scene' => 'require',
					'one_send_count' => 'require|integer|egt:1'
				],
				[
					'name.require' => '请填写优惠券名称',
					'name.unique' => '优惠券名称已存在',
					'coupon_type.require' => '请选择优惠券类型',
					'discount_price.require' => '请输入减免金额',
					'discount_price.regex' => '减免金额格式有误',
					'discount_price.egt' => '减免金额大于等于0.01',
					'expire_type.require' => '请选择到期类型',
					'expire_hour.requireIf' => '请输入有效小时',
					'expire_hour.integer' => '有效小时只能整数',
					'expire_hour.gt' => '有效小时只能大于0',
					'fixed_time_start.requireIf' => '请选择限时开始时间',
					'fixed_time_end.requireIf' => '请选择限时结束时间',
					'where_order_price.require' => '请输入订单最低金额',
					'where_order_price.regex' => '订单最低金额格式有误',
					'where_order_price.gt' => '订单最低金额必须大于减免金额',
					'limit_send_count.integer' => '发放总数量只能整数',
					'limit_send_count.egt' => '发放总数量只能大于等于0',
					'send_scene.require' => '请选择发放场景',
					'one_send_count.require' => '请输入单次发放数量',
					'one_send_count.integer' => '单次发放数量只能整数',
					'one_send_count.egt' => '单次发放数量只能大于等于1'
				]
			);
			if(true !== $validate)
			{
				echo json_encode(['code' => -1, 'msg' => $validate]);
				exit();
			}
            if (!empty($params['proxy_id'])){
                if (in_array(999,$params['proxy_id'])){
                    $params['proxy_id'] = '';
                }else{
                    $params['proxy_id'] = json_encode($params['proxy_id']);
                }
            }else{
                echo json_encode(['code' => -1, 'msg' => '请选择发放城市']);
                exit();
            }

			//基础数据
			$data = [
				'name' => $params['name'],
				'coupon_type' => $params['coupon_type'],
				'discount_value' => $params['discount_price'],
				'expire_type' => $params['expire_type'],
				'expire_hour' => $params['expire_type'] == 0 ? $params['expire_hour'] : 0,
				'fixed_time_start' => $params['expire_type'] == 1 ? strtotime($params['fixed_time_start']) : 0,
				'fixed_time_end' => $params['expire_type'] == 1 ? strtotime($params['fixed_time_end']) : 0,
				'where_order_price' => $params['where_order_price'],
				'limit_send_count' => isset($params['limit_send_count']) ? intval($params['limit_send_count']) : 0,
				'already_send_count' => isset($params['already_send_count']) ? intval($params['already_send_count']) : 0,
				'send_proxy' => $params['proxy_id'],
				'bear_one' => isset($params['bear_one']) ? $params['bear_one'] : 0,
				'send_scene' => $params['send_scene'],
				'one_send_count' => $params['one_send_count'],
				'is_enable' => isset($params['is_enable']) ? intval($params['is_enable']) : 0,
			];
			// 添加/编辑
			if(empty($params['id']))
			{
				$data['add_time'] = time();
        		$data['upd_time'] = time();
        		$coupon_id = Db::name('coupon')->insertGetId($data);
			}else
			{
				// $info = Db::name('coupon')->where(['id' => $params['id']])->find();
				// if($info['already_send_count'] > 0)
				// {
				// 	echo json_encode(['code' => -1, 'msg' => '优惠券已发放禁止修改']);
				//     exit();
				// }
				$data['upd_time'] = time();
				if(Db::name('coupon')->where(['id'=>intval($params['id'])])->update($data))
				{
					$coupon_id = $params['id'];
				}
			}
			//是否成功
			if(isset($coupon_id) && $coupon_id > 0)
			{
				$result['code'] = 0;
				$result['msg'] = "操作成功";
			}else
			{
				$result['code'] = -1;
				$result['msg'] = "操作失败";
			}
		}
		echo json_encode($result);
	}

	/**
	 * 优惠券删除
	 */
	public function delete()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		if(request()->isPost())
		{
			$params = input();
			$data = [
				'is_delete_time' => time(),
				'upd_time' => time()
			];
			if(Db::name('coupon')->where(['id' => intval($params['id'])])->update($data))
			{
				$result['code'] = 0;
				$result['msg'] = "删除成功";
			}else
			{
				$result['code'] = -1;
				$result['msg'] = "删除失败";
			}
		}
		echo json_encode($result);
	}

    public function send(){
        $coupon_list = Db::name('coupon')->where('((expire_type = 0) or (expire_type = 1 and fixed_time_end > '.time().'))  and is_delete_time = 0')->select();
        $this->assign('list',$coupon_list);
        $city = Db::name('proxy')->where('is_delete_time',0)->select();
        $this->assign('city',$city);

        $user_type = [
            ['type'=>1,'name'=>'新用户'],
            ['type'=>2,'name'=>'所有用户'],
//            ['type'=>3,'name'=>'未下单用户'],
        ];
        $this->assign('user_type',$user_type);
        return $this->fetch();
    }

    public function do_send(Request $request){
        $param = $request->param();
        if ($param['coupon_id'] == null){
            $err['code'] = -1;
            $err['msg'] = '选择优惠券';
            echo json_encode($err);die;
        }
        if (empty($param['city']) && empty($param['user_type']) && empty($param['user_mobile'])){
            $err['code'] = -1;
            $err['msg'] = '选择发放人群';
            echo json_encode($err);die;
        }
        $cp_info = Db::name('coupon')->where('id',$param['coupon_id'])->find();

        if (!empty($param['city'])){
            $city_info = Db::name('proxy')->where('proxy_id',$param['city'])->find();
            if ($city_info['is_xian'] == 1){
                $where['a.county'] = $city_info['qu'];
            }else{
                $where['a.city'] = $city_info['shi'];
                $qu = Db::name('proxy')->where('shi',$city_info['shi'])->where('proxy_id','<>',$city_info['proxy_id'])->column('qu');
                $not = implode(',',$qu);
                $where['a.county'] = ['not in',$not];
            }
            if (!empty($param['user_type'])){
                //新用户
                if ($param['user_type'] == 1){
                    $tim = time()-259200;
                    $where['u.add_time'] = ['>',$tim];
                }

            }
            $user_list = Db::name('user')
                ->alias('u')
                ->join('user_address a','u.id = a.user_id')
//                ->join('order o','o.user_id = u.id')
                ->where($where)
                ->where('a.is_default',1)
                ->column('u.id');
        }
        if (!empty($param['user_type']) && empty($param['city'])){
            //新用户
            if ($param['user_type'] == 1){
                $tim = time()-259200;
                $where['add_time'] = ['>',$tim];
            }else{
                $where['id'] = ['>',-1];
            }
            $user_list = Db::name('user')->where($where)->column('id');
        }

        if(!empty($param['user_mobile'])){
            $user_list = Db::name('user')->where('mobile',$param['user_mobile'])->column('id');
        }


        if (empty($user_list)){
            $err['code'] = -1;
            $err['msg'] = '未找到用户';
            echo json_encode($err);die;
        }
        $user_num = count($user_list);
        if ($cp_info['limit_send_count'] - $cp_info['already_send_count'] < $param['send_num'] * $user_num){
            $err['code'] = -1;
            $err['msg'] = '优惠券数量不够';
            echo json_encode($err);die;
        }

        foreach ($user_list as $value) {
            for ($i = 0; $i < $param['send_num']; $i++){
                $insert[] = [
                    'user_id' => $value,
                    'coupon_id' => $cp_info['id'],
                    'name' => $cp_info['name'],
                    'coupon_type' => $cp_info['coupon_type'],
                    'discount_value' => $cp_info['discount_value'],
                    'where_order_price' => $cp_info['where_order_price'],
                    'time_start' => !empty($cp_info['fixed_time_start']) ? $cp_info['fixed_time_start'] : time(),
                    'time_end' => !empty($cp_info['fixed_time_end']) ? $cp_info['fixed_time_end'] : time() + ($cp_info['expire_hour'] * 60 * 60),
                    'is_valid' => 1,
                    'add_time' => time(),
                ];
            }
        }
        $result = Db::name('coupon_user')->insertAll($insert);
        if ($result){
            $con_num = $param['send_num'] * $user_num + $cp_info['already_send_count'];
            $up = ['already_send_count'=>$con_num];
            Db::name('coupon')->where('id',$cp_info['id'])->update($up);
            $return['code'] = 0;
            $return['msg'] = '添加成功';
            echo json_encode($return);die;
        }
    }
}